﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public partial class ExpenseLineDislocation : IGetValue
    {
        //partial void OnLoaded()
        //{
        //    ExpenseLine e = this.ExpenseLine;
        //    e.Deleting += OnDelete;
        //}

        //public void OnDelete(object sender, EventArgs ea)
        //{
        //    ExpenseLine e = this.ExpenseLine;
        //    using (DataAccessDataContext da = new DataAccessDataContext())
        //    {
        //        da.ExpenseLineDislocations.DeleteOnSubmit(this);
        //    }
        //}

        public decimal GetExpenseValue()
        {
            //this.OnLoaded
            return Convert.ToDecimal(this.Distance) * Convert.ToDecimal(0.4);//ver aqui o 0.4
        }

        public static ExpenseLineDislocation Get(DAL.DataAccessLayer dal, Guid id)
        {
            DataAccessDataContext dc = dal.DataContext;
            IQueryable<ExpenseLineDislocation> q = from e in dc.ExpenseLineDislocations
                                                   where e.Id.Equals(id)
                                                   select e;
            int count = q.Count();
            if (count == 0)
                return null;
            ExpenseLineDislocation eld = q.First();
            return eld;
        }

        public void Save(DAL.DataAccessLayer dal)
        {
            DataAccessDataContext dc = dal.DataContext;
            var q = from eld in dc.ExpenseLineDislocations
                    where eld.Id.Equals(this.Id)
                    select eld;
            int count = q.Count<ExpenseLineDislocation>();
            ExpenseLineDislocation exp = null;
            if (count == 1)
                exp = q.First<ExpenseLineDislocation>();
            if (exp == null)
            {
                var query = from e in dc.ExpenseLines
                            where e.Id.Equals(this.Id)
                            select e;
                ExpenseLine expLine = query.Single<ExpenseLine>();
                expLine.Value = this.GetExpenseValue();
                dc.ExpenseLineDislocations.InsertOnSubmit(this);
            }
            else
            {
                exp.Arrival = this.Arrival;
                exp.Departure = this.Departure;
                exp.Distance = this.Distance;
                exp.ExpenseLine.Value = this.GetExpenseValue();
            }
            dc.SubmitChanges();
        }
    }
}
